
#include "../tools/socket.h"
#include "../tools/logging.h"

#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <algorithm>


int main()
{
    tools::CSocket s;
    s.Create();
    s.Connect("127.0.0.1", 10234);

    setbuf(stdout, NULL);

    for (int i = 0; ; i++) {
        struct timeval tv;
        tv.tv_sec = 1;
        tv.tv_usec = 0;
        fd_set  rfds;
        FD_ZERO(&rfds);
        FD_SET(STDIN_FILENO, &rfds);
        FD_SET(s.GetSocket(), &rfds);

        int ret = select(std::max(STDIN_FILENO, s.GetSocket()) + 1, &rfds, NULL, NULL, &tv);
        if (ret == 0) {
            continue;
        }
        if (ret < 0) {
            perror("select");
            break;
        }
        char buffer[1024] = {0};
        if (FD_ISSET(STDIN_FILENO, &rfds)) {
            if (fgets(buffer, sizeof(buffer), stdin)) {
                s.Send(buffer, strlen(buffer));
            }
        }
        if (FD_ISSET(s.GetSocket(), &rfds)) {
            int ret = s.Recv(buffer, sizeof(buffer));
            if (ret <= 0)
                break;
            buffer[ret] = 0;
            printf("%s", buffer);
            fflush(stdout);
        }
    }
    return 0;

}



